package com.taxshare.purchaser.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.taxshare.purchaser.entity.*;
import com.taxshare.purchaser.mapper.*;
import com.taxshare.purchaser.util.LqHttpUtil;
import com.taxshare.response.beans.Response;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.zip.GZIPInputStream;

@Slf4j
@Service
@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED)
//extends ServiceImpl<>
public class InvoiceCollectionApplyService extends ServiceImpl<InvoiceCollectionApplyMapper, InvoiceCollectionApplyEntity> {

    @Autowired
    InvoiceCollectionApplyMapper invoiceCollectionApplyMapper;
    @Autowired
    InvoiceCollectionsFjysxxMapper invoiceCollectionsFjysxxMapper;
    @Autowired
    InvoiceCollectionDetailMapper invoiceCollectionDetailMapper;
    @Autowired
    InvoiceCollectionsMapper invoiceCollectionsMapper;
    @Autowired
    invoiceAuthsMapper invoiceAuthsMapper;
    @Autowired
    InvoiceCollectionDetailService invoiceCollectionDetailService;
    @Autowired
    InvoiceCollectionsService invoiceCollectionsService;
    @Autowired
    ElectronicledgerMapper electronicledgerMapper;

    @Autowired
    CommService commService;


    private static String timeStart = " 00:00:00";
    private static String timeEnd = " 23:59:59";


    @Value("${lqpt.url}")
    private String url;

    public Map invoiceApply(Map<String, Object> param) {
        String nsrsbh = String.valueOf(param.get("nsrsbh"));
        String kprqq = String.valueOf(param.get("kprqq"));
        String kprqz = String.valueOf(param.get("kprqz"));
        String fplx = String.valueOf(param.get("fplx"));
//        String sjlx = String.valueOf(param.get("sjlx"));
        Map<String,Object> resultMap = new HashMap();
        log.info("========批量发票下载申请 ========开始======");
        JSONObject reqJson = new JSONObject();
        reqJson.put("nsrsbh",nsrsbh);
        reqJson.put("kprqq",kprqq);
        reqJson.put("kprqz",kprqz);
        //发票类型  81：电子发票（增值税专用发票）  82：电子发票（普通发票）
        reqJson.put("fplx",fplx);
        reqJson.put("sjlx","1");//数据类型1：进项票 2：销项票
//        reqJson.put("ywlsh",ptbh+ptbh+ UUIDUitl.UUID32());//流水号
        String reqStr = reqJson.toJSONString();
        log.info("========入参======>>>"+reqStr);
        try{
            url = url+"203067/PLFPXZSQ";
            LqHttpUtil lqHttpUtil = new LqHttpUtil();
            JSONObject result_json = lqHttpUtil.sendPostLq(reqStr,url);
            String returncode = result_json.getString("returncode");
            if("00".equals(returncode)) {
                String returnmsg = result_json.getString("returnmsg");
                String lsh = result_json.getString("lsh");
                InvoiceCollectionApplyEntity invoiceCollectionApplyEntity = new InvoiceCollectionApplyEntity();
                invoiceCollectionApplyEntity.setNsrsbh(nsrsbh);
                invoiceCollectionApplyEntity.setKprqq(kprqq);
                invoiceCollectionApplyEntity.setKprqz(kprqz);
                invoiceCollectionApplyEntity.setFplx(fplx);
                invoiceCollectionApplyEntity.setLsh(lsh);
                invoiceCollectionApplyEntity.setState("0");
                invoiceCollectionApplyEntity.setSjlx("1");
                invoiceCollectionApplyMapper.insertInvoiceCollectionApply(invoiceCollectionApplyEntity);
                resultMap.put("code", "0000");
                resultMap.put("msg", returnmsg);
            }
        }catch (Exception e){
            log.error("批量发票下载申请,异常：",e);
            resultMap.put("code","9999");
            resultMap.put("msg",e);
            e.printStackTrace();
        }

        log.info("========批量发票下载申请========结束======");
        return resultMap;

    }




    /*
    * 批量发票下载申请反馈
    * */
//    @Scheduled(cron = "0 */10 * * * ? ")//定时
    public void invoiceApplyFeedback(Map<String, Object> param) {
        Map<String,Object> resultMap = new HashMap();
        String lsh = "";
        int packagecount = 0;//总包数
        int packageno = 1;//当前包数


         List listLsh = invoiceCollectionApplyMapper.selectByLsh();
         if(listLsh.size()>0){
             do{
             for (int i = 0; i<listLsh.size();i++){
                  lsh = String.valueOf(listLsh.get(i));

                 log.info("========批量发票下载申请反馈 ========开始======");
                 JSONObject reqJson = new JSONObject();
                 reqJson.put("lsh",lsh);
                 reqJson.put("packageno",packageno);//数据包号，当数据量过大时会进行分包处理，初始包号 1

                 String reqStr = reqJson.toJSONString();
                 try{
                     log.info("========入参======>>>"+reqStr);
                     url = url+"203067/PLFPXZSQFK";
                     LqHttpUtil lqHttpUtil = new LqHttpUtil();
                     JSONObject result_json = lqHttpUtil.sendPostLq(reqStr,url);
                     String returncode = result_json.getString("returncode");
                     if("00".equals(returncode)) {
                         String returnmsg = result_json.getString("returnmsg");
                         int packagecounts = (int) result_json.get("packagecount");//前流水号下的总包数
                         packagecount = packagecounts;
                         String nsrsbh = result_json.getString("nsrsbh");//纳税人识别号
                         String fplx = result_json.getString("fplx");//发票类型
                         String sjlx = result_json.getString("sjlx");//数据类型1：进项票 2：销项票
                         String cljg = result_json.getString("cljg");//处理结果1：成功   2：不存在符合 条件的发票  3：失败
                         String sjl = result_json.getString("sjl");//压缩包文件流 （gzip+base64），原始数据 为 json 报文
                         // 解码并解析数据
                         String decoded = decode(sjl);
                         JSONArray jsonArray = JSONArray.parseArray(decoded);
                         for (Object obj : jsonArray) {
                             JSONObject jsonObject = (JSONObject) obj;
                             ElectronicledgerEntity entity = new ElectronicledgerEntity();
                             //删除主表重复数据
                             invoiceCollectionsMapper.deleteInvoiceCollections(jsonObject.getString("fphm"));
                             //删除明细表重复数据
                             invoiceCollectionDetailMapper.deleteInvoiceCollectionDetail(jsonObject.getString("fphm"));
                             //删除附加要素信息数据
                             invoiceCollectionsFjysxxMapper.deleteInvoiceCollectionsFjysxx(jsonObject.getString("fphm"));
                             entity.setInvoiceNo(jsonObject.getString("fphm"));
                             entity.setInvoiceType(jsonObject.getString("fplx"));
                             entity.setInvoiceDate(jsonObject.getString("kprq"));
                             entity.setFppzDm(jsonObject.getString("fppzDm"));
                             entity.setTdyslxDm(jsonObject.getString("tdyslxDm"));
                             entity.setSflzfp(jsonObject.getString("sflzfp"));
                             entity.setKjhzfpdydlzfphm(jsonObject.getString("kjhzfpdydlzfphm"));
                             entity.setKjhzfpdydzzfpDm(jsonObject.getString("kjhzfpdydzzfpDm"));
                             entity.setKjhzfpdydzzfphm(jsonObject.getString("kjhzfpdydzzfphm"));
                             entity.setSellerTaxno(jsonObject.getString("xsfnsrsbh"));
                             entity.setSellerName(jsonObject.getString("xsfmc"));
                             entity.setXhfdz(jsonObject.getString("xhfdz"));
                             entity.setPurchaserTaxno(jsonObject.getString("gmfnsrsbh"));
                             entity.setPurchaserName(jsonObject.getString("gmfmc"));
                             entity.setGmfdz(jsonObject.getString("gmfdz"));
                             entity.setAmoutWithTax((BigDecimal) jsonObject.get("hjje"));
                             entity.setTaxAmout((BigDecimal) jsonObject.get("hjse"));
                             entity.setTotalAmout((BigDecimal) jsonObject.get("jshj"));
                             entity.setJshjdx(jsonObject.getString("jshjdx"));
                             entity.setKce(jsonObject.getString("kce"));
                             entity.setJsfsDm(jsonObject.getString("jsfsDm"));
                             entity.setKpr(jsonObject.getString("kpr"));
                             entity.setBz(jsonObject.getString("bz"));
                             entity.setZzsjzjtDm(jsonObject.getString("zzsjzjtDm"));
                             entity.setCktslDm(jsonObject.getString("cktslDm"));
                             entity.setFhrxm(jsonObject.getString("fhrxm"));
                             entity.setSkrxm(jsonObject.getString("skrxm"));
                             entity.setXsfdh(jsonObject.getString("xsfdh"));
                             entity.setXsfkhh(jsonObject.getString("xsfkhh"));
                             entity.setXsfzh(jsonObject.getString("xsfzh"));
                             entity.setGmfdh(jsonObject.getString("gmfdh"));
                             entity.setGmfkhh(jsonObject.getString("gmfkhh"));
                             entity.setGmfzh(jsonObject.getString("gmfzh"));
                             entity.setXfnsrlxdm(jsonObject.getString("xfnsrlxdm"));
                             entity.setCpyycbs(jsonObject.getString("cpyycbs"));
                             entity.setAuthState("0");
                             electronicledgerMapper.insert(entity);

                             // 处理附加要素信息
                             if (jsonObject.containsKey("fjysxx")) {
                                 for (Object fjysxxObj : jsonObject.getJSONArray("fjysxx")) {
                                     JSONObject fjysxxJson = (JSONObject) fjysxxObj;
                                     if (fjysxxJson.containsKey("fjysList")) {
                                         JSONArray fjysListArray = fjysxxJson.getJSONArray("fjysList");
                                         for (Object fjysObj : fjysListArray) {
                                             JSONObject fjysJson = (JSONObject) fjysObj;
                                             // 这里可以根据实际需求处理附加要素信息，假设将第一个附加要素的名称设置到实体的某个字段
                                             if (fjysListArray.size() > 0) {
                                                 InvoiceCollectionsFjysxxEntity invoiceCollectionsFjysxxEntity = new InvoiceCollectionsFjysxxEntity();
                                                 invoiceCollectionsFjysxxEntity.setFjysKey(fjysJson.getString("fjysKey"));
                                                 invoiceCollectionsFjysxxEntity.setSjlx(fjysJson.getString("sjlx"));
                                                 invoiceCollectionsFjysxxEntity.setFjysValue(fjysJson.getString("fjysValue"));
                                                 invoiceCollectionsFjysxxEntity.setFphm(jsonObject.getString("fphm"));
                                                 invoiceCollectionsFjysxxMapper.findAllInvoiceCollectionsFjysxx(invoiceCollectionsFjysxxEntity);
                                             }
                                         }
                                     }
                                 }
                             }
                             // 处理货物信息
                             if (jsonObject.containsKey("hwxx")) {
                                 for (Object hwxxObj : jsonObject.getJSONArray("hwxx")) {
                                     JSONObject hwxxJson = (JSONObject) hwxxObj;
                                     // 这里可以根据实际需求处理货物信息，假设将第一个货物的项目名称设置到实体的某个字段
                                     if (hwxxJson.containsKey("xmmc")) {
                                         InvoiceCollectionsDetailEntity invoiceCollectionsDetailEntity = new InvoiceCollectionsDetailEntity();
                                         invoiceCollectionsDetailEntity.setFphm(hwxxJson.getString("fphm"));
                                         invoiceCollectionsDetailEntity.setFphm(hwxxJson.getString("xh"));
                                         invoiceCollectionsDetailEntity.setFphm(hwxxJson.getString("xmmc"));
                                         invoiceCollectionsDetailEntity.setFphm(hwxxJson.getString("spfwjc"));
                                         invoiceCollectionsDetailEntity.setFphm(hwxxJson.getString("hwhyslwfwmc"));
                                         invoiceCollectionsDetailEntity.setFphm(hwxxJson.getString("sphfwssflhbbm"));
                                         invoiceCollectionsDetailEntity.setFphm(hwxxJson.getString("ggxh"));
                                         invoiceCollectionsDetailEntity.setFphm(hwxxJson.getString("dw"));
                                         invoiceCollectionsDetailEntity.setFphm(hwxxJson.getString("fpjysl"));
                                         invoiceCollectionsDetailEntity.setFphm(hwxxJson.getString("fpjydj"));
                                         invoiceCollectionsDetailEntity.setFphm(hwxxJson.getString("slv"));
                                         invoiceCollectionsDetailEntity.setFphm(hwxxJson.getString("se"));
                                         invoiceCollectionsDetailEntity.setFphm(hwxxJson.getString("je"));
                                         invoiceCollectionsDetailEntity.setFphm(hwxxJson.getString("kce"));
                                         invoiceCollectionDetailMapper.insertInvoiceCollectionDetail(invoiceCollectionsDetailEntity);
                                     }
                                 }
                             }
                         }
                         packageno++;
                         //当前包数大于总包数时  说明这个流水号相关的数据都下载完成了  那就把状态改成已反馈
                         if (packageno > packagecounts){
                             invoiceCollectionApplyMapper.updateByLsh(lsh);
                         }
//                        System.out.println(decoded);

                     }
                 }catch (Exception e){
                     log.error("批量发票下载申请反馈,异常：",e);
                     resultMap.put("code","9999");
                     resultMap.put("msg",e);
                     e.printStackTrace();
                 }
             }
             }while(packageno <= packagecount);
         }

        resultMap.put("code", "0000");
        resultMap.put("msg", "成功");
        log.info("========批量发票下载申请反馈========结束======");


    }



    public static String decode(String encoded) throws IOException {
        // 解码Base64字符串
        byte[] compressedBytes = Base64.getDecoder().decode(encoded);

        // 创建一个GZIP输入流来解压数据
        try (ByteArrayInputStream bis = new ByteArrayInputStream(compressedBytes);
             ByteArrayOutputStream bos = new ByteArrayOutputStream();
             GZIPInputStream gis = new GZIPInputStream(bis)) {

            byte[] buffer = new byte[1024];
            int len;

            // 将解压后的数据写入输出流
            while ((len = gis.read(buffer)) > 0) {
                bos.write(buffer, 0, len);
            }

            // 获取解压后的数据
            return new String(bos.toByteArray(), "UTF-8");
        }
    }



    public static void main(String[] args) {
        try {
            // 示例Gzip+Base64编码的字符串
            String encoded = "H4sIAAAAAAAAAO2a2VIbRxSGX2VKV7ZLo+rumdEsd8QmJHGQHROyYW6IIisKSilWKhJQVIXECGwQAic2xuCSARO7CFsSbBYBfhn1zOiKV8hp7QItw2KIiFQFxVEvanWf7/9PC3X02TwBr9+m2YioqjJiD6ciY1UkENrstu8Cd39grYiIPFJ5InJY0kRBE0Ro9AQCvdfYYEQgCnq6ez0BiL6EIBz0fB+8G+zyQqxiAacnJpKKsVNUlEwH/9fQSF8s0q1/zOEt+mB2f2c4ublMp3f3d+7rM/dTU+N0cInGNqH7HX/xfKqKsg9BwULTF5kOluczp57qI3EafZTcjcJQr8/3DYxUBNmBxXQcZDFyIASRL+j1Fbey2B2GZ/ToaHJ3jcYG9JE9Pf6QzkTo/Jb58qH5S4QORzJ7d4wF0Z2fjYVXdOIJzNDVCxOYw4v60qx23dUM29jGcZxdj41DXxrb0No+aCIIEQVJgp0Or10y/khc1jdX9ckFfSauwakhHmGeSPs7o+b8ICwCGrWrLhhmN6ZXjKf3WNzS3tLeatdfb5hvx831LTvX3naNjsXpy5HU0ERq7llyc1vDBNn1v4aMsSEWOR2q7CR2c3UjmVgw9sbo4K/JxBN9aY8drN8f9gZh3ZgF7NS6w25/Nvb4eoJhtnl9t9N/f/xt8MfbNo3r6OxnGx9ibR19trA3N96fPtRkYt4Yj2SWxzIt4An52PNGImZsL2Za9Zko7HB6Fm9PsDvkCaWHXjnc58qh6byeUBDS19vVxRYqIBEpsHUYfrIPlmB30qsq2nF40h1iq1h4lYYB3k937n1C4C5Jm2D3T9mcys6Xz7FsXJyD/Z399mpkquXJdGpY1iS1QWaDzAaZ50CmgBAuT6asYUUjSoPMBpkNMs+HTFKJTCJVrWZdbJzPC4G7x82eq4Z+HSLMV2eYPwzxJXM9rj9au3xmMM/9aWzP0cjf5m/P6PIkvLTx+2sam2C9YhvG8wGNK3ccHBu0PJnpmHw7qw+sGrMr5soLeBlj5zGTAi6zo0REqsISlEgIKVxDPOpLPPiTqAdvUT6ESvIhYLgPXzhjx5BuDglVUoVCc14VgP1kIg46AJqQmoqAJpjra6AJyZ0oaMKpW7sTSa5iLtsxgTTBiiiV55Lw+BCX738Ew4q4vOr6tOlGDS6JIBVxKcMmIHQ+XKam7tEHz08f0NJ5j0Jq4Qys2HwmhyyDmku5WqCKFUEVNSydgs8L9Uk0XwNpvgzTOac/M7aP5fTC8ZxelbmGltSvlvAnERO+tpoIxCk604JxUE2c7DNwIoDzXzzbxwKqchkoNB+wffY7dxU4r0s9VhGRZVk9fl1+s+XWjVu16nLIG9QozXOleW7TLRl+PnssOn62fy1GnRUZdVYtzS04fkEE6hBmvgbNfBmcSx3/bLA+oulnz+QYpi/KApJqXe8bMvLfkxH+RDrCWxASVSSCWs7sVSYkEtJE+cKZvVNyyEolccg15pUhU/dDxQ9CADcBEAI9Ovou/P2zT75i56I2F3P5oQuKQTgoKJErgYmhLFdLwGxrgXElNTkDtQaYpVBKsnLmJTkdfJNMPM4v+zQBrTD1UWAtOgkrpp/LI2uoZnrX4rSc4avs398ieP7JPsovCEEdAs1XJZo/hHTO7M8A7aN6fOYYjuzxbD9xweMbUlLnUsKfQEt4a2JS5ltuAuKwyL5LQy6e6RNYoEPElUSi0JxXCXN9Da4Cqek3xZ/8wSUAZAIuBO/kht/a3IIwVj8vqcxvtsF+ELbJZbHFKo9kHqOqpfn15tb3mux0aJvG5qvDKxyozhVZlP+n1Xlm45FqzfALGWQN01x/4LTzX2xCJo2PKgAA";

            // 解码并打印结果
            String decoded = decode(encoded);
            System.out.println(decoded);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
